import { Controller, Get, Query, Res } from '@nestjs/common';
import { DataService } from './data.service';
import { ModuleSwaggerTags } from '~/constants/modules.constant';
import { ApiBearerAuth, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { DashboardMetric } from './data.type';
import { StandardPagination } from '~/helper/paginate';
import { ExcelService } from '../tools/excel/excel.service';
import { FastifyReply } from 'fastify';
import { AllowAnon } from '../auth/decorators/allow-anon.decorator';
import { ApiResult } from '~/common/decorators/api-result.decorator';

@AllowAnon()
@ApiTags(ModuleSwaggerTags.DATA)
@ApiBearerAuth()
@Controller('cms/data')
export class DataController {
  constructor(
    private readonly dataService: DataService,
    private readonly excelService: ExcelService
  ) {}

  @ApiOperation({
    summary: '查询面板数据 - 今日阅读量、今日任务完成总数、今日答题次数、答题正确率',
  })
  @Get('panel')
  async getPanelData(): Promise<DashboardMetric[]> {
    return await this.dataService.getPanelData();
  }

  @ApiOperation({ summary: '查询用户列表 - 分页' })
  @ApiQuery({ name: 'page', required: true, description: '页码' })
  @ApiQuery({ name: 'pageSize', required: true, description: '每页数量' })
  @ApiQuery({ name: 'diseaseId', required: false, description: '疾病ID' })
  @ApiQuery({ name: 'keyword', required: false, description: '关键词搜索' })
  @Get('panel/user')
  async getPanelUserPage(
    @Query('page') page: number,
    @Query('pageSize') pageSize: number,
    @Query('diseaseId') diseaseId?: number,
    @Query('keyword') keyword?: string
  ): Promise<StandardPagination<any>> {
    return await this.dataService.getPanelDataWithUser({
      page,
      pageSize,
      diseaseId,
      keyword,
    });
  }

  @ApiOperation({ summary: '导出用户列表数据' })
  @ApiQuery({ name: 'diseaseId', required: false, description: '疾病ID' })
  @ApiQuery({ name: 'keyword', required: false, description: '关键词搜索' })
  @Get('panel/user/export')
  async exportPanelUserList(
    @Res() res: FastifyReply,
    @Query('diseaseId') diseaseId?: number,
    @Query('keyword') keyword?: string
  ): Promise<void> {
    try {
      const { columns, data } = await this.dataService.exportPanelUserList(diseaseId, keyword);
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('用户数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `用户列表数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  @ApiOperation({ summary: '导出文章列表数据' })
  @Get('panel/article/export')
  async exportPanelArticleList(@Res() res: FastifyReply): Promise<void> {
    try {
      const { columns, data } = await this.dataService.exportPanelArticleList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('文章数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `文章列表数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  @Get('panel/feedback/export')
  @ApiOperation({ summary: '导出用户反馈数据' })
  @ApiResult({ type: Object, isPage: false })
  async exportPanelFeedbackList(@Res() res: FastifyReply): Promise<any> {
    try {
      const { columns, data } = await this.dataService.exportPanelFeedbackList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('用户反馈数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `用户反馈数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  @Get('panel/points/export')
  @ApiOperation({ summary: '导出积分日志数据' })
  @ApiResult({ type: Object, isPage: false })
  async exportPanelPointsLog(@Res() res: FastifyReply): Promise<any> {
    try {
      const { columns, data } = await this.dataService.exportPanelPointsLogList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('积分日志数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `积分日志数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  @Get('panel/article/log/export')
  @ApiOperation({ summary: '导出文章阅读数据' })
  @ApiResult({ type: Object, isPage: false })
  async exportPanelArticleLog(@Res() res: FastifyReply): Promise<any> {
    try {
      const { columns, data } = await this.dataService.exportPanelArticleLogList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('文章阅读数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `文章阅读数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  // 文章评分记录
  @Get('panel/article/review/log/export')
  @ApiOperation({ summary: '导出文章评分数据' })
  @ApiResult({ type: Object, isPage: false })
  async exportPanelArticleReviewLog(@Res() res: FastifyReply): Promise<void> {
    try {
      const { columns, data } = await this.dataService.exportPanelArticleReviewLogList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createWorkbook('文章评分数据', columns, data);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `文章评分数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
  }

  // 文章点赞/收藏/转发记录
  @Get('panel/article/count/export')
  @ApiOperation({ summary: '导出文章相关统计数据' })
  @ApiResult({ type: Object, isPage: false })
  async exportPanelArticleRelatedCount(@Res() res: FastifyReply): Promise<void> {
		try {
      const sheetConfig = await this.dataService.exportPanelArticleRelatedCountList();
      // 创建Excel工作簿
      const workbook = await this.excelService.createMultiSheetWorkbook(sheetConfig);

      // 将工作簿转换为Buffer
      const buffer = await this.excelService.workbookToBuffer(workbook);

      // 设置响应头
      const filename = `文章关联统计数据_${new Date().toISOString().slice(0, 10)}.xlsx`;
      res.header(
        'Content-Type',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      );
      res.header('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);

      // 发送文件
      return res.send(buffer);
    } catch (error) {
      return res.status(500).send({
        statusCode: 500,
        message: `导出Excel文件失败: ${error.message}`,
        error: 'Internal Server Error',
      });
    }
	}
}
